﻿using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc;
using System.DirectoryServices.Protocols;
using System.Net;
using SimpleInOutControl.Common;

namespace SimpleInOutControl.Utility
{
    public class ExceptionHandlingFilter : IAsyncExceptionFilter
    {
        private readonly ILogger<ExceptionHandlingFilter> _logger;
        private readonly IHostEnvironment _hostEnvironment;

        public ExceptionHandlingFilter(ILogger<ExceptionHandlingFilter> logger, IHostEnvironment hostEnvironment)
        {
            _logger = logger;
            _hostEnvironment = hostEnvironment;
        }

        public Task OnExceptionAsync(ExceptionContext context)
        {
            Exception exception = context.Exception;

            _logger.LogError(exception, exception.Message);

            var response = new ResponseResult<string>
            {
                Code = -1,
                Message = exception.Message,
                Result=""
            };

            //if (_hostEnvironment.IsDevelopment())
            //{
            //    response.Message = exception.Message;
            //}
            //else
            //{
            //    response.Message = "服务器异常，请稍后重试";
            //}

            ObjectResult result = new ObjectResult(response);

            int statusCode = -1;
            switch (exception)
            {
                case ApplicationException:
                    {
                        if (exception.Message.Contains("Invalid token"))
                        {
                            statusCode = (int)HttpStatusCode.Forbidden;
                            break;
                        }
                        statusCode = (int)HttpStatusCode.BadRequest;
                        break;
                    }
                case KeyNotFoundException:
                    {
                        statusCode = (int)HttpStatusCode.NotFound;
                        break;
                    }
                default:
                    {
                        statusCode = (int)HttpStatusCode.InternalServerError;
                        break;
                    }
            }
            result.StatusCode = statusCode;
            context.Result = result;
            context.ExceptionHandled = true;

            return Task.CompletedTask;
        }
    }
}
